public class Sort {


    /**
     * 直接插入排序
     */
    public static void insertSort(int[] array) {

        for (int i = 0; i < array.length; i++) {
            int j = i-1;
            int tmp = array[i];
            for (; j >=0 ; j--) {
                if(array[j] > tmp) {
                    array[j+1] = array[j];
                }else {
                    break;
                }
            }
            array[j+1] = tmp;
        }
    }
    /**
     *  希尔排序
     */
    public static void shellSort(int[] array) {
        int gap = array.length;
        while (gap > 1) {
            gap = gap/2;
            shell(array,gap);
        }
    }
    public static void shell(int[] array,int gap) {

        for (int i = gap; i < array.length; i++) {
            int tmp = array[i];
            int j = i-gap;
            for (; j >= 0 ; j-=gap) {
                if(array[j] > tmp) {
                    array[j+gap] = array[j];
                }else {
                    break;
                }
            }
            array[j+gap] = tmp;
        }
    }
    /**
     *  直接选择排序
     */
    public static void selectSort(int[] array) {

        for (int i = 0; i < array.length-1; i++) {
            int minIndex = i;//记录当前下标
            int j = i+1;
            for(;j < array.length;j++) {
                if(array[j]<array[minIndex]) {
                    minIndex = j;//最小值下标更新
                }
            }
            swap(array,i,minIndex);
        }

    }
    public static void swap(int[] array,int i,int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    /**
     *  冒泡排序
     */
    public static void  bubbleSort(int[] array) {

        for (int i = 0; i < array.length-1; i++) {
            boolean bool = true;
            for (int j = 0; j < array.length-i-1; j++) {
                if(array[j] > array[j+1]) {
                    bool = false;
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
            if(bool) {
                break;
            }
        }
    }

    /**
     *  计数排序
     */
    public static void countSort(int[] array) {
        //1.求最值
        int max = array[0];
        int min = array[0];
        for (int i = 1; i < array.length; i++) {
            if(array[i] > max) {
                max = array[i];
            }
            if(array[i] < min) {
                min = array[i];
            }
        }
        //2.创建计数数组并初始化
        int[] count = new int[max-min+1];
        //3.遍历数组
        for (int i = 0; i < array.length; i++) {
            int index = array[i];
            count[index-min]++;
        }
        //4.取出计数数组
        int k = 0;
        for (int i = 0; i < count.length; i++) {
            int len = count[i];

           while (len != 0) {
               array[k] = i+min;
               k++;
               len--;
           }
        }
    }

}
